﻿using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace KINLO.DRV.Drv
{ 

    public class ElectronicBalanceSocketDrv
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(ElectronicBalanceSocketDrv));
        public string IpAddr;
        public int Port;
        Socket socket;
        public ElectronicBalanceSocketDrv(string ip, int port)
        {
            try
            {
                this.IpAddr = ip;
                this.Port = port;
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.ReceiveTimeout = 1500;
                socket.SendTimeout = 1500;
                Open();
            }
            catch (Exception ex)
            {
                var msg = string.Format("创建电子称 {0},{1} 发生异常:", IpAddr, Port, ex.Message);
                log.Info(msg);
                Messenger.Default.Send(msg, "ReceiveEventInfo"); 
            }
        }
        public bool BlnConnected { get; set; }
        public void Open()
        {
            try
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.ReceiveTimeout = 1500;
                socket.SendTimeout = 1500;
                socket.Connect(IpAddr, Port);
                if (!isExceptioning)
                {
                    Log(string.Format("打开电子称 {0},{1}", IpAddr, Port));
                    isExceptioning = false;
                }
            }
            catch (Exception ex)
            {
                socket.Close();
                if (!isExceptioning)
                {
                    isExceptioning = true;
                    Log(string.Format("打开电子称 {0},{1} 发生异常:", IpAddr, Port, ex.Message));
                }
            }
        }
        public void Close()
        {
            try
            {
                socket.Close();
                Log(string.Format("关闭电子称{0},{1}", IpAddr, Port));
            }
            catch (Exception ex)
            {
                Log(string.Format("关闭电子称异常 {0},{1} {2}", IpAddr, Port, ex.Message));
            }
        }
        public int FindCRIndex(byte[] bytes)
        {
            var sign = Encoding.Default.GetBytes("\n")[0];
            for (var i = bytes.Length - 1; i > 0; i--)
            {
                if (bytes[i] == sign)
                    return i;
            }
            return -1;
        }
        List<byte> buff = new List<byte>();
        public byte[] Read()
        {
            try
            {
                while (true)
                {
                    var buf = new byte[1024];
                    var len = socket.Receive(buf);
                    BlnConnected = (len > 0 ? true : false);
                    isExceptioning = (len > 0 ? false : true);
                    var buff1 = buf.Take(len).ToArray();
                    buff.AddRange(buff1);
                    var index1 = buff.ToList().LastIndexOf(10);
                    if (index1 >= 19)
                    {
                        var result1 = buff.Skip(index1 - 19).Take(20).ToArray();
                        return result1;
                    }
                    if (len == 0)
                    {
                        Open();
                    }
                }
            }
            catch (SocketException sex)
            {
                //Logger.WarningGlobal($"{ID}:{IP}:{Port} 2电子称连接已断开");
                Open();
                return null;
            }
            catch (Exception ex)
            {
                BlnConnected = false;
                if (!isExceptioning)
                {
                    isExceptioning = true;
                }
                Open();
                return null;
            }
            finally
            {
                buff.Clear();
            }
        }

        public byte[] Read2()
        {
            try
            {
                var buff = new byte[10240];
                var len = socket.Receive(buff);
                BlnConnected = (len > 0 ? true : false);
                isExceptioning = (len > 0 ? false : true);
                var buff1 = buff.Take(len).ToArray();
                var index = FindCRIndex(buff1);
                var result = buff1.Skip(index - 19).Take(20).ToArray();
                if (len == 0)
                {
                    Open();
                }
                return result;
            }
            catch (Exception ex)
            {
                BlnConnected = false;
                if (!isExceptioning)
                {
                    Log(string.Format("电子称 {0},{1} 发生异常:{2}", IpAddr, Port, ex.Message));
                    isExceptioning = true;
                }
                Open();
                return null;
            }
        }

        bool isExceptioning = false;
        public void ClearZero()
        {
            try
            {
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(IpAddr, Port);
                var b = Encoding.Default.GetBytes("DZ\r\n");
                var b1 = Encoding.Default.GetBytes("5");
                socket.Send(b);
                socket.Send(b1);
                socket.Close();
            }
            catch (Exception ex)
            {
                Log(string.Format("电子称:{0},{1} 清零时发生异常:{2}", IpAddr, Port, ex.Message));
            }
        }

        public void Log(string msg)
        { 
            log.Info(msg);
            Messenger.Default.Send(msg, "ReceiveEventInfo");
        }
    }


}
